package com.ecommerce.product.service.impl;

import com.ecommerce.common.core.ApiResult;
import com.ecommerce.common.core.PageResult;
import com.ecommerce.product.dto.ProductInfo;
import com.ecommerce.product.dto.ProductQueryRequest;
import com.ecommerce.product.entity.Product;
import com.ecommerce.product.repository.ProductRepository;
import com.ecommerce.product.service.ProductService;
import jakarta.persistence.criteria.Predicate;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Override
    public List<ProductInfo> getProductsByIds(List<Long> productIds) {
        List<Product> products = productRepository.findAllByIdIn(productIds);
        return products.stream()
                .map(product -> ProductInfo.builder()
                        .id(product.getId())
                        .name(product.getName())
                        .price(product.getPrice())
                        .status(product.getStatus())
                        .build())
                .collect(Collectors.toList());
    }

    @Override
    public ApiResult<PageResult<Product>> pageProducts(ProductQueryRequest request) {
        Pageable pageable = PageRequest.of(request.getPage() - 1, request.getSize());
        
        Specification<Product> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            if (StringUtils.hasText(request.getKeyword())) {
                predicates.add(criteriaBuilder.like(
                    root.get("name"), "%" + request.getKeyword() + "%"));
            }
            
            if (request.getStatus() != null) {
                predicates.add(criteriaBuilder.equal(
                    root.get("status"), request.getStatus()));
            }
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        
        Page<Product> page = productRepository.findAll(spec, pageable);
        PageResult<Product> pageResult = PageResult.of(
            page.getNumber() + 1,
            page.getSize(),
            page.getTotalElements(),
            page.getContent()
        );
        return ApiResult.success(pageResult);
    }

    @Override
    public ApiResult<Product> getProductById(Long id) {
        return productRepository.findById(id)
                .map(ApiResult::success)
                .orElse(ApiResult.error("商品不存在"));
    }

    @Override
    public ApiResult<Product> createProduct(Product product) {
        product.setId(null);
        Product saved = productRepository.save(product);
        return ApiResult.success(saved);
    }

    @Override
    public ApiResult<Product> updateProduct(Long id, Product product) {
        if (!productRepository.existsById(id)) {
            return ApiResult.error("商品不存在");
        }
        product.setId(id);
        Product updated = productRepository.save(product);
        return ApiResult.success(updated);
    }

    @Override
    public ApiResult<Void> deleteProduct(Long id) {
        if (!productRepository.existsById(id)) {
            return ApiResult.error("商品不存在");
        }
        productRepository.deleteById(id);
        return ApiResult.success(null);
    }
}